using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Skywave.ComponentModel.Log
{
    /// <summary>
    /// Provides easy functions for text logging.
    /// </summary>
    [System.ComponentModel.Design.HelpKeyword("Provides easy functions for text logging")]
    public class TextLog
    {
        /*
         * w= Implements a text writer for writing characters.
         */
        StreamWriter w;
        /// <summary>
        /// This class opens or creates the particular file including the current day.
        /// </summary>
        /// <param name="logDirPath"> The directory path to store log file.</param>
        /// <param name="logFileName"> The name of the destination log file.</param>
        public TextLog(string logDirPath, string logFileName)
        {
            /*
             * curDT=Stores the current date
             * fs1=Supports random access to files using seek method. Used to read from, write to, open or close files.
             */

            DateTime curDT = DateTime.Now;
            if (logFileName.ToLower().IndexOf(".txt") < 0)
                logFileName += " " + curDT.Year.ToString() + "-" + curDT.Month.ToString("00") + "-" +
                    curDT.Day.ToString("00") + ".txt";
            if (!Directory.Exists(logDirPath)) Directory.CreateDirectory(logDirPath);

            FileStream fs1 = new FileStream(logDirPath + logFileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
            fs1.Seek(0, SeekOrigin.End);
            w = new StreamWriter(fs1);
        }
        ~TextLog()
        {
            End();
        }
        /// <summary>
        /// Starts a new section in Log file.
        /// </summary>
        public void Start()
        {
            Start("");
        }
        /// <summary>
        /// Starts a new section in Log file and appends custom additional information.
        /// </summary>
        /// <param name="additionalInfo"> Appended additional information except the date.</param>
        public void Start(string additionalInfo)
        {
            w.WriteLine("\r\nStart Log : DateTime = " + DateTime.Now.ToString() + " " + additionalInfo);
            w.Flush();
        }
        /// <summary>
        ///  Adds new log line to the started section.
        /// </summary>
        /// <param name="title">Title for the specified log.</param>
        /// <param name="desc">The explanation of the log entry.</param>
        public void WriteLog(string title, string desc)
        {
            w.WriteLine("\t{0}\t{1}\t{2}", DateTime.Now, title, desc);
            w.Flush();
        }
        /// <summary>
        /// Checks for validity of file address and closes the file.
        /// </summary>
        public void End()
        {
            if (w != null && w.BaseStream != null && w.BaseStream.CanWrite) { w.Flush(); w.Close(); }
        }
    }
}
